package com.robot.admin.controller;

import com.alibaba.fastjson.JSON;
import com.robot.admin.client.*;
import com.robot.admin.pojo.Admin;
import com.robot.admin.pojo.client.*;
import com.robot.admin.service.AdminService;
import com.robot.admin.util.SendMessageUtil;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import util.GeoHashUtil;
import util.IdWorker;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 后台商户入驻申请模块
 *
 * @author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/merchant_apply")
public class MerchantApplyController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private MemberClient memberClient;
    @Autowired
    private MerchantClient merchantClient;

    @Autowired
    private AgentClient agentClient;

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private HttpServletRequest request;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SendMessageUtil sendMessageUtil;

    /**
     * merchant_apply表status状态 0-初审待审核 1-初审通过 2-初审失败 3-平台待审核 4-平台审核通过 5-平台审核失败
     */

    private String merchantApplyStatusSecondTrialSuccess = "4";
    private String merchantApplyStatusSecondTrialFailed = "5";

    /**
     * 当该地区暂无代理商代理时设为系统代理商id
     */
    @Value("${sys.agent.agentId}")
    private String sysAgentAgentId;


    /**
     * merchant_apply列表并分页
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "{page}/{size}", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Result findMerchantApplies(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        Admin adminInDb = adminService.findById(claims.getId());
        logger.info("adminInDb=" + adminInDb);
        if (adminInDb == null) {
            return new Result(StatusCode.ERROR_ADMIN_DOES_NOTE_EXIST);
        }

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(memberClient.thirdFindMerchantAppliesBySearch(searchMap, page, size)));
    }

    /**
     * 通过id查询merchant_apply详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "{id}", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public Result findMerchantApply(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        Admin adminInDb = adminService.findById(claims.getId());
        logger.info("adminInDb=" + adminInDb);
        if (adminInDb == null) {
            return new Result(StatusCode.ERROR_ADMIN_DOES_NOTE_EXIST);
        }

        MerchantApply merchantApplyInDb = JSON.parseObject(memberClient.thirdFindMerchantApplyById(id), MerchantApply.class);
        logger.info("merchantApplyInDb=" + merchantApplyInDb);
        if (merchantApplyInDb == null) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        if (merchantApplyInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR, "该商户入驻审核申请单已被删除");
        }
        return new Result(StatusCode.SUCCESS_QUERY, merchantApplyInDb);
    }

    /**
     * 通过id审核merchant_apply
     *
     * @param apply
     * @param id
     * @return
     */
    @RequestMapping(value = "/secondTrial/{status}/{id}", method = RequestMethod.PUT, produces = "application/json; charset=utf-8")
    @Transactional(rollbackFor = Exception.class)
    public Result secondTrialMerchantApply(@RequestBody MerchantApply apply, @PathVariable String status, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        Admin adminInDb = adminService.findById(claims.getId());
        logger.info("adminInDb=" + adminInDb);
        if (adminInDb == null) {
            return new Result(StatusCode.ERROR_ADMIN_DOES_NOTE_EXIST);
        }

        logger.info("apply=" + apply);
        MerchantApply merchantApplyInDb = JSON.parseObject(memberClient.thirdFindMerchantApplyById(id), MerchantApply.class);
        logger.info("merchantApplyInDb=" + merchantApplyInDb);
        if (merchantApplyInDb == null) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        if (merchantApplyInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR, "该商户入驻审核申请单已被删除");
        }
        if (merchantApplyStatusSecondTrialSuccess.equals(merchantApplyInDb.getStatus())) {
            return new Result(StatusCode.ERROR, "该商家入驻申请单平台已审核通过");
        }

        if (merchantApplyStatusSecondTrialSuccess.equals(status) || merchantApplyStatusSecondTrialFailed.equals(status)) {
            //审核通过
            if (merchantApplyStatusSecondTrialSuccess.equals(status)) {
                //判断手机号是否已被店铺使用
                Store storeInDb = JSON.parseObject(merchantClient.thirdFindStoreByPhone(merchantApplyInDb.getPhone()), Store.class);
                logger.info("判断手机号是否唯一" + storeInDb);
                if (storeInDb != null) {
                    return new Result(StatusCode.ERROR, "手机号已被使用,请换个手机号");
                }

                Member memberInDb = JSON.parseObject(memberClient.thirdFindMemberById(merchantApplyInDb.getMemberId()), Member.class);
                Agent agentInDb = JSON.parseObject(agentClient.thirdFindAgentByAreaIdAndStatusAndDeletedAtIsNull(merchantApplyInDb.getAreaId(), "1"), Agent.class);
                logger.info("agentInDb=" + agentInDb);
                String agentId = sysAgentAgentId;
                if (agentInDb == null) {
                    logger.info("agentInDb is null,so company and store's agentId is null");
                } else {
                    agentId = agentInDb.getId();
                }
                //待审核更新为审核通过,则新增一公司一店铺
                Company company = addCompany(merchantApplyInDb, memberInDb, agentId);
                //待审核更新为审核通过,则新增一公司一店铺
                Store store = addStore(merchantApplyInDb, memberInDb, agentId);

                merchantClient.thirdAddCompany(JSON.toJSONString(company));
                merchantClient.thirdAddStore(JSON.toJSONString(store));
                merchantApplyInDb.setStatus(status);
            } else if (merchantApplyStatusSecondTrialFailed.equals(status)) {
                if (apply.getRemark() == null || "".equals(apply.getRemark())) {
                    return new Result(StatusCode.ERROR, "驳回原因必填");
                }
                merchantApplyInDb.setStatus(status);
                merchantApplyInDb.setRemark(apply.getRemark());
            }
            memberClient.thirdUpdateMerchantApply(JSON.toJSONString(merchantApplyInDb));
            return new Result(StatusCode.SUCCESS);
        } else {
            return new Result(StatusCode.ERROR, "审核状态=" + status + "错误");
        }
    }

    /**
     * 删除merchant_apply
     *
     * @param id
     */
    @PutMapping(value = "deleteMerchantApply/{id}")
    @Transactional(rollbackFor = Exception.class)
    public Result deleteMerchantApply(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        Admin adminInDb = adminService.findById(claims.getId());
        logger.info("adminInDb=" + adminInDb);
        if (adminInDb == null) {
            return new Result(StatusCode.ERROR_ADMIN_DOES_NOTE_EXIST);
        }

        MerchantApply merchantApplyInDb = JSON.parseObject(memberClient.thirdFindMerchantApplyById(id), MerchantApply.class);
        logger.info("merchantApplyInDb=" + merchantApplyInDb);
        if (merchantApplyInDb == null) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        merchantApplyInDb.setDeletedAt(LocalDateTime.now());
        memberClient.thirdUpdateMerchantApply(JSON.toJSONString(merchantApplyInDb));
        return new Result(StatusCode.SUCCESS_DELETED);
    }

    /**
     * 消息推送
     *
     * @param map
     * @return
     */
    @PostMapping("messagePush")
    public Result sendSms(@RequestBody Map map) {
        Map<String, Object> resultMap = sendMessageUtil.sendMessage(map);
        return new Result(StatusCode.SUCCESS_SEND);
    }

    /**
     * 待审核更新为审核通过,则新增一公司
     *
     * @param merchantApplyInDb
     * @param memberInDb
     * @param agentId
     * @return
     */
    public Company addCompany(MerchantApply merchantApplyInDb, Member memberInDb, String agentId) {
        Company company = new Company();
        company.setId(merchantApplyInDb.getCompanyId());
        company.setCompanyName(merchantApplyInDb.getCompanyName());
        company.setAgentId(agentId);
        company.setContact(merchantApplyInDb.getContract());
        company.setPhone(merchantApplyInDb.getPhone());
        company.setRealName(memberInDb.getRealName());
        company.setRealNameStatus(memberInDb.getRealNameStatus());
        company.setIdCard(merchantApplyInDb.getIdCard());
        company.setIdCardFront(merchantApplyInDb.getIdCardFront());
        company.setIdCardBack(merchantApplyInDb.getIdCardBack());
        company.setBusinessLicense(merchantApplyInDb.getBusinessLicense());
        company.setBusinessLicenseImg(merchantApplyInDb.getBusinessLicenseImg());
        company.setProvinceId(merchantApplyInDb.getProvinceId());
        company.setProvince(merchantApplyInDb.getProvince());
        company.setCityId(merchantApplyInDb.getCityId());
        company.setCity(merchantApplyInDb.getCity());
        company.setAreaId(merchantApplyInDb.getAreaId());
        company.setArea(merchantApplyInDb.getArea());
        company.setAddress(merchantApplyInDb.getAddress());
        company.setIsChain(merchantApplyInDb.getIsChain());
        logger.info("company" + company);
        return company;
    }

    /**
     * 待审核更新为审核通过,则新增一店铺
     *
     * @param merchantApplyInDb
     * @param memberInDb
     * @param agentId
     * @return
     */
    public Store addStore(MerchantApply merchantApplyInDb, Member memberInDb, String agentId) {
        Store store = new Store();

        store.setId(merchantApplyInDb.getStoreId());
        store.setStoreName(merchantApplyInDb.getStoreName());
        store.setCompanyId(merchantApplyInDb.getCompanyId());
        store.setAgentId(agentId);
        store.setMemberId(merchantApplyInDb.getMemberId());
        store.setContact(merchantApplyInDb.getContract());
        store.setPhone(merchantApplyInDb.getPhone());
        store.setEmail(merchantApplyInDb.getEmail());
        store.setBusinessLicense(merchantApplyInDb.getBusinessLicense());
        store.setBusinessLicenseImg(merchantApplyInDb.getBusinessLicenseImg());

        store.setLongitude(merchantApplyInDb.getLongitude());
        store.setLatitude(merchantApplyInDb.getLatitude());
        if (merchantApplyInDb.getLatitude() != null && !"".equals(merchantApplyInDb.getLatitude()) && merchantApplyInDb.getLatitude() != null && !"".equals(merchantApplyInDb.getLatitude())) {
            GeoHashUtil geoHashUtil = new GeoHashUtil();
            String geoHash = geoHashUtil.encode(Double.parseDouble(merchantApplyInDb.getLatitude()), Double.parseDouble(merchantApplyInDb.getLongitude()));
            String halfGeoHash = geoHashUtil.halfGeoHash(Double.parseDouble(merchantApplyInDb.getLatitude()), Double.parseDouble(merchantApplyInDb.getLongitude()));
            logger.info("geoHash=" + geoHash);
            logger.info("halfGeoHash=" + halfGeoHash);
            store.setGeoHash(geoHash);
            store.setHalfGeoHash(halfGeoHash);
        }

        store.setIndustryId(merchantApplyInDb.getIndustryId());
        store.setIndustryLicense(merchantApplyInDb.getIndustryLicense());
        store.setIndustryLicenseImg(merchantApplyInDb.getIndustryLicenseImg());
        store.setRealName(memberInDb.getRealName());
        store.setRealNameStatus(memberInDb.getRealNameStatus());
        store.setIdCard(merchantApplyInDb.getIdCard());
        store.setIdCardFront(merchantApplyInDb.getIdCardFront());
        store.setIdCardBack(merchantApplyInDb.getIdCardBack());
        store.setProvinceId(merchantApplyInDb.getProvinceId());
        store.setProvince(merchantApplyInDb.getProvince());
        store.setCityId(merchantApplyInDb.getCityId());
        store.setCity(merchantApplyInDb.getCity());
        store.setAreaId(merchantApplyInDb.getAreaId());
        store.setArea(merchantApplyInDb.getArea());
        store.setAddress(merchantApplyInDb.getAddress());
        store.setOpenId(memberInDb.getOpenId());
        store.setUnionId(memberInDb.getUnionId());
        store.setCoverImage(merchantApplyInDb.getCoverImage());
        store.setImages(merchantApplyInDb.getImages());
        store.setRate(merchantApplyInDb.getRate());
        logger.info("store's rate=" + merchantApplyInDb.getRate());

        store.setRecommendId(merchantApplyInDb.getRecommendId());
        store.setFreight(0.0);
        store.setPacking(0.0);
        store.setStatus("1");
        logger.info("store" + store);
        return store;
    }
}
